package com.ygxsk.carhome.ui.repair;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundLinearLayout;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.AppointmentStatus;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CustomerStateType;
import com.ygxsk.carhome.enumwrap.PermissionsIsSend;
import com.ygxsk.carhome.enumwrap.ToDoor;
import com.ygxsk.carhome.event.EventRepariMain;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.EvaluateWadeInfo;
import com.ygxsk.carhome.response.HandleVoList;
import com.ygxsk.carhome.response.RepairManageDetailBean;
import com.ygxsk.carhome.response.RepairManageItemBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusCarWade;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.evaluate.EvaluateWadePopu;
import com.ygxsk.carhome.ui.leads.LeadManagerGroupActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.StringCodeUtils;
import com.ygxsk.carhome.utils.ViewUitls;
import com.ygxsk.carhome.views.FJEditTextCountPublish;
import com.ygxsk.carhome.views.picker.CustomDatePicker;
import com.ygxsk.carhome.views.picker.DateFormatUtils;
import com.ygxsk.carhome.views.picker.WeekUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-19  15:03
 * @Description:预约维保的详情内容，只有顶部信息的
 */
public class RepairDetailActivity extends ErrorActivity implements ErrorParentExtraSingle {

    //保存按钮
    @BindView(R.id.layoutbuttonrepairsave)
    RoundTextView roundButtonRepairSave;

    //分配客户的按钮内容
    @BindView(R.id.roundbuttondistributerepair)
    RoundTextView roundButtonDistributeRepair;

    //车牌号
    @BindView(R.id.textviewcarnumbernametop)
    TextView textViewCarNumberNameTop;

    //预约车辆的信息
    @BindView(R.id.textviewcarbaseinfotop)
    TextView textViewCarBaseInfoTop;

    //车辆的里程数量
//    @BindView(R.id.textviewcarmileage)
//    TextView textViewCarmMileage;

    //车辆的服务顾问，就是评估师或者维修师傅
    @BindView(R.id.textviewcarrepirmanager)
    TextView textViewCarRepirManager;

    //车辆的服务顾问的名称
    @BindView(R.id.textviewcarmanagername)
    TextView textViewCarManagerName;

    //车辆的预约时间
    @BindView(R.id.textviewcarbookingtime)
    TextView textViewCarBookingTime;

    //车辆的 是否是上门取车
    @BindView(R.id.textviewcardoorget)
    TextView textViewCarDoorGet;

    //联系方式
    @BindView(R.id.textviewcontactway)
    TextView textViewContactWay;

    //用户状态的外侧点击
    @BindView(R.id.layoutrepairforcustomer)
    LinearLayout layoutRepairForCustomerStatus;

    //客户的分配状态
    @BindView(R.id.textviewcarassignedstate)
    TextView textViewCarAssignedState;

    //整个改约时间 的包裹模块
    @BindView(R.id.linearlayoutchangebookingtime)
    RoundLinearLayout linearLayoutChangeBookingTime;

    //修改预约时间 改约时间 的外部点击包裹
    @BindView(R.id.layoutcarbookingtimeoutside)
    LinearLayout layoutCarBookingTimeOutside;

    //修改预约时间 改约时间
    @BindView(R.id.textviewcarrepairbookingtime)
    TextView textViewCarRepairBookingTime;

    //改约的原因备注信息
    @BindView(R.id.editviewchangebookingtimeremark)
    FJEditTextCountPublish editViewChangeBookingTimeRemark;

    //整个改约时间 的包裹模块
    @BindView(R.id.linearlayoutcancelreason)
    RoundLinearLayout linearLayoutCancelReason;

    //改约的原因备注信息
    @BindView(R.id.editviewcancelrepairremark)
    FJEditTextCountPublish editViewCancelRepairRemark;

    @BindView(R.id.textviewhelpinrepairdetail)
    TextView textViewHelpInRepairDetail;

    //private ArrayList<CustomerStateTypeInfo> mDataResources_customerStateType = new ArrayList();
    private ArrayList<EvaluateWadeInfo> mDataResources_customerStateType = new ArrayList();
//    private ArrayList<EvaluateWadeInfo> mDataResources_temp_list = new ArrayList();

    //预约维保管理
    private RepairManageItemBean extra_repair_manage_item_bean;

    //预约改约的时间；
    private String appointmentTime_upLoad;

    //客户的分配状态
    private String assignedState_upLoad;

    //待确认的 客户状态弹窗；
    private BasePopupView basePopupView_customerState;


    @OnClick({R.id.linelayoutcallphoneindetai,//拨打电话
            R.id.layoutcarbookingtimeoutside,//改约时间的外侧包裹
            R.id.layoutbuttonrepairsave,//保存按钮【可能是取消预约可能是修改预约时间】
            R.id.roundbuttondistributerepair,//分配客户按钮内容
            R.id.layoutrepairforcustomer//选择客户的状态，分别对应 底部布局的改约或者取消
    })//
    public void onViewClickedInDetail(View v) {

        switch (v.getId()) {

            case R.id.roundbuttondistributerepair: {

                KeyboardUtils.hideSoftInput(mActivityInstance);

                Bundle extra_bundle = new Bundle();
                //是 预约维保 的分配过来的
                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_REPAIR_DETAIL_ACTIVITY);
                //携带 这个预约维保的信息过去
                extra_bundle.putParcelable(ExtraKey.EXTRA_REPAIR_MANAGE_ITEM_BEAN, extra_repair_manage_item_bean);

                ActivityUtils.startActivity(extra_bundle, LeadManagerGroupActivity.class);

                break;
            }

            case R.id.layoutrepairforcustomer: {
                //
                //价格和涉水的类型相互转换
//                ArrayList<EvaluateWadeInfo> tempList = new ArrayList<>();
//                for (CustomerStateTypeInfo customerStateTypeInfo : //
//                        mDataResources_customerStateType) {
//                    EvaluateWadeInfo evaluateWadeInfo = new EvaluateWadeInfo();
//                    evaluateWadeInfo.setDictCode(customerStateTypeInfo.getDictCode());
//                    evaluateWadeInfo.setDictLabel(customerStateTypeInfo.getDictLabel());
//                    tempList.add(evaluateWadeInfo);
//                }

                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_FORM_HISTORY) {

                        //如果是从历史记录进来的 ,那么这个不可编辑，是什么状态就展示什么状态
//                    PopTip.show("不可编辑")
//                            .setButton("立即清理", new OnDialogButtonClickListener<PopTip>() {
//                        @Override
//                        public boolean onClick(PopTip baseDialog, View v) {
//                            //toast("点击了立即清理");
//                            return false;
//                        }
//                    }).iconWarning();

                        PopTip.show(StringUtils.getString(R.string.statuscannotedit)).iconWarning();


                    } else {

                        //直接弹窗：
                        EvaluateWadePopu evaluateWadePopu = new EvaluateWadePopu(RepairDetailActivity.this,//
                                ExtraValue.MODIFY_EVALUATE_CUSTOMER_STATE_SELECT,//
                                mDataResources_customerStateType);
                        evaluateWadePopu.setTitleName(getResources().getString(R.string.repair_car_assigned));

                        basePopupView_customerState = new XPopup.Builder(RepairDetailActivity.this)//
                                .hasShadowBg(true)//
                                .isViewMode(true)//
                                .asCustom(evaluateWadePopu)//
                                .show();
                    }
                }

                break;
            }

            case R.id.linelayoutcallphoneindetai: {

                //callPhone
                clickButton_toCallPhone(RepairDetailActivity.this, extra_repair_manage_item_bean.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_3.getIndex());

                break;
            }

            case R.id.layoutcarbookingtimeoutside: {

                initTimerPicker();

                break;
            }

            case R.id.layoutbuttonrepairsave: {//【保存】按钮

                //如果时【修改约定时间】那么验证改约时间的空
                if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CHANGE_BOOKING_TIME) {

                    if (TextUtils.isEmpty(appointmentTime_upLoad)) {
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_booking_time_upload), true);
                        mAlertView.show();
                        return;
                    }

                    //只有一个单个点击
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.clearaddorsubmitsuremessage),//提示内容
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainSubmitChangeBookingTime_upLoad();

                            }
                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();


                } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CANCEL_BOOKING) {
                    //如果是取消预约，那么取消原因要不要验证？

                    //只有一个单个点击
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_repair_cancel_message),//提示内容：确定取消预约吗
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainSubmitCancelBooking_upLoad(extra_repair_manage_item_bean.getAppointmentId());

                            }
                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                } else if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_INTO) {


                    //如果仅仅是从 item 的点击过来的，那么需要判断
                    if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_SUREED.getIndex())) {

                        //已确认 和客户联系。，那么备注和改约，取消原因等 都不展示

                        CommUtils.checkDialog(mAlertView);
                        mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                StringUtils.getString(R.string.submit_sure_message), //提示内容:已确认和客户取得联系
                                StringUtils.getString(R.string.clearcachecancel), //取消
                                new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {

                                    method_gainSureContactSubmitInfo_upLoad(extra_repair_manage_item_bean.getAppointmentId());

                                }
                            }
                        });

                        mAlertView.setCancelable(true);
                        mAlertView.show();

                    } else if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_CANCELED.getIndex())) {
                        //已取消，填写取消原因，直接提交

                        CommUtils.checkDialog(mAlertView);
                        mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                StringUtils.getString(R.string.submit_repair_cancel_message),//提示内容确定取消预约吗？
                                StringUtils.getString(R.string.clearcachecancel), //取消
                                new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {

                                    method_gainSubmitCancelBooking_upLoad(extra_repair_manage_item_bean.getAppointmentId());

                                }
                            }
                        });

                        mAlertView.setCancelable(true);
                        mAlertView.show();

                    } else if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_COMPLETED_AND_INTO_STATION.getIndex())) {
                        //已完成--已进站 算是流程结束；

                        CommUtils.checkDialog(mAlertView);
                        mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                StringUtils.getString(R.string.alert_repair_station_into),//确认已联系；
                                StringUtils.getString(R.string.clearcachecancel), //取消
                                new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {

                                    method_gainSubmitIntoStation_upLoad(extra_repair_manage_item_bean.getAppointmentId());

                                }

                            }
                        });

                        mAlertView.setCancelable(true);
                        mAlertView.show();

                    }
                }

                break;
            }

            default:
                break;
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

//        initloading();

        initViews();

        gainDatas();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_repair_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setTitle(getString(R.string.car_repair_detail));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //应该是 还没有【被分配】被评估完毕的，还是可以再次编辑的
        // TODO: 2023-07-18 11:34 判断该订单的状态，是否是还可以再次编辑 ??
        toolbarHelper.setLayoutRight(false, 0, "", null);
//        toolbarHelper.setLayoutRight(false, 0, "编辑", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//                //历史记录的页面布局
//                Bundle extra_bundle = new Bundle();
////                //这里空携带,,编辑信息 ？
//                ActivityUtils.startActivity(extra_bundle, CarEvaluateAddSubmitActivity.class);
//
//            }
//        });

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }


    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initViews() {

        //初始化数据
        if (mDataResources_customerStateType == null) {
            mDataResources_customerStateType = new ArrayList<>();
        }

        if (mDataResources_customerStateType != null) {
            mDataResources_customerStateType.addAll(ViewUitls.getCustomerStateTypesWadeCustom());
        }

        //如果是【修改预约时间】那么展示外侧布局
        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CHANGE_BOOKING_TIME) {

            CommUtils.setViewGone(linearLayoutCancelReason);
            CommUtils.setViewVisible(linearLayoutChangeBookingTime);

            //隐藏【客户状态】
            CommUtils.setViewGone(layoutRepairForCustomerStatus);

            //那么外侧时间包裹可点击
        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CANCEL_BOOKING) {

            //如果是【取消预约维保】那么不展示改约外侧，展示取消外侧.
            CommUtils.setViewGone(linearLayoutChangeBookingTime);
            CommUtils.setViewVisible(linearLayoutCancelReason);

            //隐藏【客户状态】
            CommUtils.setViewGone(layoutRepairForCustomerStatus);

        } else if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_INTO) {

            //【分配客户】按钮隐藏
            CommUtils.setViewGone(roundButtonDistributeRepair);

            //隐藏【客户状态】--并且是【可编辑】状态
            CommUtils.setViewVisible(layoutRepairForCustomerStatus);

        } else if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_FORM_HISTORY) {
            //如果是从 历史记录进来，没有点击

            //确定按钮的点击 是不可用的
//            if (layoutRepairForCustomer!=null){
//                layoutRepairForCustomer.setClickable(false);
//                layoutRepairForCustomer.setFocusable(false);
//                layoutRepairForCustomer.setEnabled(false);
//            }

            //【保存】按钮隐藏
            CommUtils.setViewGone(roundButtonRepairSave);
            //【分配客户】按钮隐藏
            CommUtils.setViewGone(roundButtonDistributeRepair);

            //展示【客户状态】--但是，是【不可编辑】状态
            CommUtils.setViewVisible(layoutRepairForCustomerStatus);

            //取消原因，的编辑框 不可用
            if (editViewCancelRepairRemark != null) {
                editViewCancelRepairRemark.getEditText().setEnabled(false);
            }

        } else {

            //不符合的 都是隐藏
            CommUtils.setViewGone(linearLayoutChangeBookingTime);
            CommUtils.setViewGone(linearLayoutCancelReason);
            //隐藏【客户状态】
            CommUtils.setViewGone(layoutRepairForCustomerStatus);

        }

        //底部帮助软键盘布局
        CommUtils.methodHelpView(textViewHelpInRepairDetail);

        //监听客户状态的填充
        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusCarWade.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusCarWade>() {

                    @Override
                    public void accept(RxBusCarWade rxBusCarWade) throws Throwable {

                        if (rxBusCarWade != null) {

                            if (rxBusCarWade.getActionFlag() == ExtraValue.MODIFY_EVALUATE_CUSTOMER_STATE_SELECT) {//【预约维保的类型】；

//                                        STATE_HAS_SUREED(1,"已确认"),
//                                        STATE_HAS_DISPATCH(2,"已分配"),
//                                        STATE_HAS_CANCELED(3,"已取消"),
//                                        STATE_HAS_COMPLETED(4,"已完成"),
//                                        STATE_NOT_DISPATCH(5,"待分配");

                                //车辆涉水的id
                                assignedState_upLoad = rxBusCarWade.getEvaluateWadeInfo().getDictCode();

                                Delivery.getInstance().post(new Runnable() {
                                    @Override
                                    public void run() {

                                        //修改文本:客户的状态
                                        if (textViewCarAssignedState != null) {
                                            textViewCarAssignedState.setText(rxBusCarWade.getEvaluateWadeInfo().getDictLabel());
                                        }

                                        if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_SUREED.getIndex())) {
                                            //已确认 和客户联系。，那么备注和改约，取消原因等 都不展示
                                            CommUtils.setViewGone(linearLayoutChangeBookingTime);
                                            CommUtils.setViewGone(linearLayoutCancelReason);
                                        } else if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_CANCELED.getIndex())) {
                                            //已取消，填写取消原因，直接提交
                                            CommUtils.setViewGone(linearLayoutChangeBookingTime);
                                            CommUtils.setViewVisible(linearLayoutCancelReason);
                                        } else if (TextUtils.equals(assignedState_upLoad, CustomerStateType.STATE_HAS_COMPLETED_AND_INTO_STATION.getIndex())) {
                                            //已完成
                                            CommUtils.setViewGone(linearLayoutChangeBookingTime);
                                            CommUtils.setViewGone(linearLayoutCancelReason);
                                        }

                                    }
                                });
                            }
                        }
                    }
                }));

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {
            getServerDatas();
        } else {
            //是否有其他的执行逻辑？
            netWorkError();
        }

    }

    //确定已进站的接口
    private void method_gainSubmitIntoStation_upLoad(String _appointmentId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.appointmentId, _appointmentId);//这条数据的id

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEFORDONE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateForDone_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateForDone(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RepairDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //{"data":"","message":"无更多数据","code":"29999"}
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                        //这里仅仅是给提示
                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {
                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        //通知主页列表刷新
                        EventRepariMain eventRepariMain = new EventRepariMain();
                        eventRepariMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_REPAIR_MAIN_LIST);
                        EventBus.getDefault().post(eventRepariMain);

                        //该页面关闭，
                        methodSubmitSuccess(RepairDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                methodBack();
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //retain
                    }
                });


    }

    //取消预约接口
    private void method_gainSubmitCancelBooking_upLoad(String _appointmentId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.appointmentId, _appointmentId);//这条数据的id
        map.put(Parameterkey.handleContent, editViewCancelRepairRemark.getText().toString().trim());//这条数据的id

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEFORCANCEL_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateForCancel_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateForCancel(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RepairDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {
                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        //通知主页列表刷新
                        EventRepariMain eventRepariMain = new EventRepariMain();
                        eventRepariMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_REPAIR_MAIN_LIST);
                        EventBus.getDefault().post(eventRepariMain);
                        //该页面关闭，
                        methodSubmitSuccess(RepairDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                methodBack();
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //retain
                    }
                });


    }

    //确认已经和客户取得联系
    private void method_gainSureContactSubmitInfo_upLoad(String _appointmentId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.appointmentId, _appointmentId);//这条数据的id

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEFORDOING_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateForDoing_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateForDoing(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RepairDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {
                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        //通知主页列表刷新
                        EventRepariMain eventRepariMain = new EventRepariMain();
                        eventRepariMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_REPAIR_MAIN_LIST);
                        EventBus.getDefault().post(eventRepariMain);

                        //该页面关闭，
                        methodSubmitSuccess(RepairDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                methodBack();
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //retain
                    }
                });

    }

    //提交修改预约时间的接口
    private void method_gainSubmitChangeBookingTime_upLoad() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.appointmentId, extra_repair_manage_item_bean.getAppointmentId());//
        map.put(Parameterkey.changeAppointmentTime, appointmentTime_upLoad);//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEAPPOINTMENT);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateAppointment_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateAppointment(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(RepairDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知主页列表刷新
                        EventRepariMain eventRepariMain = new EventRepariMain();
                        eventRepariMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_REPAIR_MAIN_LIST);
                        EventBus.getDefault().post(eventRepariMain);

                        methodSubmitSuccess(RepairDetailActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                methodBack();
                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });

    }


    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.appointmentId, extra_repair_manage_item_bean.getAppointmentId());//,预约维保记录ID

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getShopLatentCustomerList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
//                .getDetailById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
//                        MediaType.parse(ApiService.HEADER_JSON)))
                .getDetailById(extra_repair_manage_item_bean.getAppointmentId())
                .compose(RepairDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<RepairManageDetailBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        methodNotSuccessData(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        //
                    }
                }).subscribe(new Consumer<RepairManageDetailBean>() {
                    @Override
                    public void accept(RepairManageDetailBean repairManageDetailBean) throws Throwable {

                        if (repairManageDetailBean != null) {

                            if (extra_repair_manage_item_bean != null) {
                                //id也需要重新设置一次
                                extra_repair_manage_item_bean.setAppointmentId(String.valueOf(repairManageDetailBean.getAppointmentId()));
                                //涉及到外侧拨打电话，需重新赋值
                                extra_repair_manage_item_bean.setPhone(repairManageDetailBean.getPhone());
                            }

                            method_handler_success(repairManageDetailBean);
                        }
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错；
                        function_apiException(apiException);
                    }
                });

    }

    private void method_handler_success(RepairManageDetailBean _repairManageDetailBean) {

        Delivery.getInstance().post(new Runnable() {
            @Override
            public void run() {

                //车牌号
                CommUtils.setText(textViewCarNumberNameTop, _repairManageDetailBean.getCarNo());
                //预约车辆信息
                CommUtils.setText(textViewCarBaseInfoTop, _repairManageDetailBean.getCarBrandName() + getString(R.string.kongge0) + _repairManageDetailBean.getCarSeriesName() + getString(R.string.kongge0) + _repairManageDetailBean.getVehicleName());
                //车辆的里程数量
//                CommUtils.setText(textViewCarmMileage, String.valueOf(_repairManageDetailBean.getMileage()));
                //车辆的里程数量
//                String mileResult = "";
//                if (_repairManageDetailBean.getMileage() != null) {
//                    CommUtils.setText(textViewCarmMileage, _repairManageDetailBean.getMileage().toString());
//                } else {
//                    CommUtils.setText(textViewCarmMileage, CommUtils.formatComma2BigDecimal(0.00).toString());
//                }
                // : 2023-08-10 20:07 服务顾问字段有疑问？
                //车辆的服务顾问，就是评估师或者维修师傅
                CommUtils.setText(textViewCarRepirManager, _repairManageDetailBean.getCustomerName());

                //车辆的顾问  2023年10月21日15:17:51 新增的
                CommUtils.setText(textViewCarManagerName, _repairManageDetailBean.getManagerName());


                //车辆的预约时间
                //2023-9-7 11:17:30 预约时间的展示 有规则限制：
                //2、显示预约时间：优先展示changeAppointmentTime，如果changeAppointmentTime为空，展示预约日期+预约时段（appointmentTime+expectedPeriod）
                //2、显示预约时间：优先展示changeAppointmentTime，如果changeAppointmentTime为空，展示预约日期+预约时段（appointmentTime+expectedPeriod）
                String timeResult = "";
                //选中的预约时间
                String changeAppointmentTime = _repairManageDetailBean.getChangeAppointmentTime();
                //预约日期
                String appointmentTime = _repairManageDetailBean.getAppointmentTime();
                //预约时间段
                String expectedPeriod = _repairManageDetailBean.getExpectedPeriod();

                if (!TextUtils.isEmpty(changeAppointmentTime)) {
                    timeResult = changeAppointmentTime;
                } else {
                    timeResult = appointmentTime + StringUtils.getString(R.string.kongge0) + expectedPeriod;
                }

                CommUtils.setText(textViewCarBookingTime, timeResult);


                //车辆的 是否是上门取车 "isToDoor": 1, //是否上门取车：0否；1是
                int isToDoor = _repairManageDetailBean.getIsToDoor();
                if (isToDoor == ToDoor.TO_DOOR_YES.getIndex()) {
                    CommUtils.setText(textViewCarDoorGet, ToDoor.TO_DOOR_YES.getValue());
                } else if (isToDoor == ToDoor.TO_DOOR_NO.getIndex()) {
                    CommUtils.setText(textViewCarDoorGet, ToDoor.TO_DOOR_NO.getValue());
                }

                //联系方式 是最后一个
//                CommUtils.setText(textViewContactWay, _repairManageDetailBean.getPhone());
                CommUtils.setText(textViewContactWay, StringCodeUtils.mobileEncrypt(_repairManageDetailBean.getPhone()));

                //客户的状态： 如果是从历史记录进来的，要直接展示，并且不可编辑
                if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_FORM_HISTORY) {

//                             nodo(0, "待处理"),
//                            sended(1, "已分配"),
//                            taked(2, "已接单"),
//                            doing(3, "已确认"),
//                            done(4, "已完成"),
//                            canceled(5, "已取消"),

                    //判断状态，然后给备注展示出来
                    int handleStatus = _repairManageDetailBean.getHandleStatus();
                    CommUtils.setText(textViewCarAssignedState, _repairManageDetailBean.getHandleStatusInfo());
                    ArrayList<HandleVoList> handleVoLists = _repairManageDetailBean.getHandleVoList();


                    if (handleStatus == AppointmentStatus.canceled.getCode()) {//已取消

                        //显示已取消 的原因
                        CommUtils.setViewVisible(linearLayoutCancelReason);

                        if (handleVoLists != null && !handleVoLists.isEmpty()) {

                            for (HandleVoList item : handleVoLists) {

                                int itemStatus = item.getHandleStatus();
                                String handleContent = item.getHandleContent();//改约或者取消的原因；

//                                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--handleContent-->" + handleContent);

                                if (handleStatus == itemStatus) {

//                                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--handleContent-->发现匹配的");

                                    if (editViewCancelRepairRemark != null) {
                                        //只能展示不能编辑的
                                        editViewCancelRepairRemark.getEditText().setEnabled(false);
                                        editViewCancelRepairRemark.getEditText().setFocusable(false);
                                        editViewCancelRepairRemark.getEditText().setPressed(false);
                                        editViewCancelRepairRemark.setText(handleContent);
                                    }

                                }
                            }

                        }
                    }
                }


                //底部按钮是否有【分配客户】的权限
                //处理【分配客户】的按钮
                int isSend = _repairManageDetailBean.getIsSend();

                if (isSend == PermissionsIsSend.IS_SEND_CAN.getIndex()) {

                    if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_INTO) {
                        //只有是正常的，从【点击条目】进来，才能有可能展示【分配客户】
                        roundButtonDistributeRepair.setVisibility(View.VISIBLE);

                    } else if (flag_jumpfrom_where == ExtraValue.MODIFY_EVALUATE_CUSTOMER_ONITEM_CLICK_FORM_HISTORY) {

                        //如果是历史记录过来的-即便是有权限-也隐藏
                        roundButtonDistributeRepair.setVisibility(View.GONE);
                        roundButtonRepairSave.setVisibility(View.GONE);

                    } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CHANGE_BOOKING_TIME) {

                        //如果是【改约】过来的，也隐藏
                        roundButtonDistributeRepair.setVisibility(View.GONE);

                    } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CANCEL_BOOKING) {

                        //如果是 取消预约 过来的，必然隐藏
                        roundButtonDistributeRepair.setVisibility(View.GONE);

                    } else {
                        //其他 就直接隐藏
                        roundButtonDistributeRepair.setVisibility(View.GONE);
                    }

                } else if (isSend == PermissionsIsSend.IS_SEND_NOT.getIndex()) {
                    //只要是 没有权限，任何时候都不展示【分配客户】
                    roundButtonDistributeRepair.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (basePopupView_customerState != null) {
            basePopupView_customerState.onDestroy();
            basePopupView_customerState = null;
        }
    }

    @Override
    protected void methodBack() {

        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }

    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);
            //
            extra_repair_manage_item_bean = bundle.getParcelable(ExtraKey.EXTRA_REPAIR_MANAGE_ITEM_BEAN);
            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            LogUtils.json(ConstantSign.LOGCAT_NOMAL, extra_repair_manage_item_bean);

        }


    }

    //直接拨打电话的能力
//    private void clickButton_toCallPhone(Activity _activity, String mPhoneNumber) {
//
//        CommUtils.checkDialog(mAlertView);
//
//        //二次确认弹窗提示
//        mAlertView = new AlertView(ConstantSign.ALERTVIEW_TITLE_FOR_PHONE,//
//                mPhoneNumber, //
//                ConstantSign.ALERTVIEW_LEFT_CANCEL,//
//                new String[]{ConstantSign.ALERTVIEW_RIGHT_COPY_INFORMATION}, //
//                null, //
//                _activity, //
//                AlertView.Style.Alert,//
//                new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(Object o, int position) {
//
//                        if (position != AlertView.CANCELPOSITION) {
//
//                            if (!TextUtils.isEmpty(mPhoneNumber)) {
//                                _activity.startActivity(CommUtils.callThePhoneNumAction_dial(mPhoneNumber));
//                            } else {
//                                ToastUtils.showShort(R.string.hasfailgetphonenumber);
//                            }
//
//                        }
//                    }
//                }
//        );
//
//        mAlertView.setCancelable(true).show();
//
//    }

    private void initTimerPicker() {

        //String beginTime = "2018-10-17 18:00";
        String beginTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);
        //获取当前年份
        int currentYear = WeekUtils.getYearSingleForYearDialog() + 1;
        String endTime = currentYear + "-12-12 18:00";//DateFormatUtils.long2Str(System.currentTimeMillis(), true);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "endTime-->" + endTime);

        //mTvSelectedTime.setText(endTime);
        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        CustomDatePicker mTimerPicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {

            @Override
            public void onTimeSelected(long timestamp) {

                Delivery.getInstance().post(new Runnable() {

                    @Override
                    public void run() {

                        //添加一个时间戳的内容:人为的手动添加 秒，不然的话 是行不通的。
                        //serviceTimeUpload = "2021-10-17 18:00:00";
                        appointmentTime_upLoad = DateFormatUtils.long2Str(timestamp, true) + ":00";

                        //那个改约时间的填充
                        if (textViewCarRepairBookingTime != null) {
                            textViewCarRepairBookingTime.setText(DateFormatUtils.long2Str(timestamp, true));
                        }

                    }
                });

            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);

        //默认显示当前的时间
        //SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()

        //第二种格式：
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//等价于now.toLocaleString()

        String curSelectedTime = TimeUtils.getNowString(simpleDateFormat);

        if (mTimerPicker != null) {
            mTimerPicker.show(curSelectedTime);
        }

    }

}